package io.p2p.stream.p2pmain.handler;

import com.alibaba.fastjson.JSONObject;
import common.core.domain.udp.UdpApiProtocol;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.DatagramPacket;
import io.p2p.stream.p2pmain.session.ActiveNodeSessionManager;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * 客户端心跳协议类
 */
@Slf4j
public class ClientHeartbeatHandler {

    private UdpApiProtocol apiProtocol;

    public ClientHeartbeatHandler(UdpApiProtocol apiProtocol) {
        this.apiProtocol = apiProtocol;
    }

    public void clientHeartbeat() {
        String loginName = apiProtocol.getBuffer().getString("name");

        String clientIp = apiProtocol.getRemoteIP();
        int clientPort = apiProtocol.getRemotePort();

        //刷新节点
        ActiveNodeSessionManager.getInstance().flush(loginName,clientIp,clientPort);

        //log.info("Received client heartbeat data at IP: {},Port: {},Name: {}.",clientIp,clientPort,loginName);

        //发送心跳应答指令给客户端
        JSONObject ack = new JSONObject();
        ack.put("type","mainHeartbeatAck");

        String msg = String.format("Client at IP: %s,Port: %s,Name: %s is active.",clientIp,clientPort,loginName);
        ack.put("msg",msg);

        apiProtocol.getCtx().writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                ack.toJSONString(), StandardCharsets.UTF_8), new InetSocketAddress(clientIp,clientPort)));
    }
}
